package com.tcwlkj.uuService.service;

import android.Manifest;
import android.app.ActivityManager;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.IBinder;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.util.Log;
import android.widget.Toast;

import com.baidu.location.BDLocation;
import com.baidu.location.BDLocationListener;
import com.baidu.location.LocationClient;
import com.baidu.location.LocationClientOption;
import com.iflytek.cloud.ErrorCode;
import com.iflytek.cloud.SpeechConstant;
import com.iflytek.cloud.SpeechError;
import com.iflytek.cloud.SpeechSynthesizer;
import com.iflytek.cloud.SynthesizerListener;
import com.tcwlkj.uuService.MyApp;
import com.tcwlkj.uuService.NetWork.HttpCallBack;
import com.tcwlkj.uuService.NetWork.RetrofitUtils;
import com.tcwlkj.uuService.R;
import com.tcwlkj.uuService.enums.CheckStatus;
import com.tcwlkj.uuService.model.CommonResponse;
import com.tcwlkj.uuService.model.DeviceModle;
import com.tcwlkj.uuService.model.LocationModel;
import com.tcwlkj.uuService.model.MainMessage;
import com.tcwlkj.uuService.ui.BaseActivity;

import com.tcwlkj.uuService.utils.ChcheUtils;
import com.tcwlkj.uuService.utils.EventCenter;
import com.tcwlkj.uuService.utils.PreferencesUtils;
import com.tcwlkj.uuService.utils.Tools;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.List;

import retrofit2.Call;

/**
 * Created by Administrator on 2017/10/26 0026.
 */

public class LocationService extends Service {


    private LocationModel locationModel = new LocationModel(0d, 0d);

    private LocationClient mLocationClient;//定位的客户端
    private MyLocationListener mMyLocationListener;//定位的监听器
    /**
     * 最新一次的经纬度
     */
    private double mCurrentLantitude;
    private double mCurrentLongitude;
    private DeviceModle deviceModle;
    @Override
    public void onCreate() {
        super.onCreate();
        initMyLocation();
    }
    private void updateLocation() {

        deviceModle = new DeviceModle("0", Tools.getDeviceModel(), Tools.getDeviceSystemVersion(), Tools.getVersion(getApplicationContext()),
                Tools.getIPAddress(getApplicationContext()), Tools.isNotificationEnabled(getApplicationContext()), Tools.getLocalMacAddressFromIp(getApplicationContext()), Tools.isLocationEnabled(getApplicationContext()));
        Call<CommonResponse> httpResultCall = RetrofitUtils.getRequest(this, false).updateLocation(PreferencesUtils.getString(MyApp.getContext(),"userID"),Tools.javabeanToJson(locationModel),Tools.javabeanToJson(deviceModle),PreferencesUtils.getString(MyApp.getContext(),"oridIdList"),PreferencesUtils.getInt(MyApp.getContext(),PreferencesUtils.getString(MyApp.getContext(), "userID")+"work",5)+"");
        httpResultCall.enqueue(new HttpCallBack<CommonResponse>() {
            @Override
            public void onSuccess(Object t) {
                Log.d("123","success");
            }

            @Override
            public void onFail(int code, String message) {

            }
        });
    }


    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        flags= START_NOT_STICKY;
        return super.onStartCommand(intent, flags, startId);
    }

    private void initMyLocation() {
        // 定位初始化
        mLocationClient = new LocationClient(getApplicationContext());
        mMyLocationListener =new MyLocationListener();
        mLocationClient.registerLocationListener(mMyLocationListener);
        // 设置定位的相关配置
        LocationClientOption option = new LocationClientOption();
        option.setOpenGps(true);// 打开gps
        option.setLocationMode(LocationClientOption.LocationMode.Hight_Accuracy);// 设置定位模式
        option.setIsNeedAddress(true);//返回的定位结果包含地址信息
        option.setCoorType("bd09ll"); // 设置坐标类型  只适用百度地图  火星坐标系
        option.setScanSpan(30000);
        mLocationClient.setLocOption(option);
        if (!mLocationClient.isStarted()) {
            mLocationClient.start();
        }
    }
    private String mCurrentAddress = "";
    public class MyLocationListener implements BDLocationListener {
        @Override
        public void onReceiveLocation(BDLocation location) {
            // map view 销毁后不在处理新接收的位置
            if (location == null)
                return;
            /**
             * 最新一次的经纬度
             */
            mCurrentAddress = location.getAddrStr();
            mCurrentLantitude = location.getLatitude();
            mCurrentLongitude = location.getLongitude();
            // 第一次定位时，将地图位置移动到当前位置

            if (!TextUtils.isEmpty(mCurrentAddress)) {
                locationModel.setLng(mCurrentLongitude);
                locationModel.setLat(mCurrentLantitude);
            } else {
                mCurrentAddress = "暂无位置信息";
                if(ChcheUtils.getInstance().getLocationModel()!=null){
                    locationModel=ChcheUtils.getInstance().getLocationModel();
                }else {
                    locationModel.setLng(0d);
                    locationModel.setLat(0d);
                }
            }
            Log.d("location",mCurrentLantitude+"-----"+mCurrentLongitude);

//            ActivityManager mActivityManager = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);
//            List<ActivityManager.RunningAppProcessInfo> listOfProcesses = mActivityManager.getRunningAppProcesses();
//            for (ActivityManager.RunningAppProcessInfo process : listOfProcesses) {
//                Log.e("Process Running", process.processName);
//                if (process.processName.equals("com.tcwlkj.uuService")) {
//                    Log.d("123","123123");
//                }else {
//                    Log.d("123","321321");
//                }
//            }
            ChcheUtils.getInstance().setLocationModel(locationModel);
            EventBus.getDefault().post(new EventCenter<String>(101,"位置更新"));
            if(PreferencesUtils.getBoolean(MyApp.getContext(),"Login")){
                updateLocation();
            }
        }
    }
    @Override
    public void onDestroy() {
        super.onDestroy();
    }
    @Override
    public boolean onUnbind(Intent intent) {
        return super.onUnbind(intent);
    }

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }
}
